package com.zsc.newbuds.controller;

import com.sun.net.httpserver.Authenticator;
import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.entity.User;
import com.zsc.newbuds.service.impl.AdminServiceImpl;
import com.zsc.newbuds.service.impl.UserServiceImpl;
import com.zsc.newbuds.utils.RedisUtil;
import com.zsc.newbuds.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author D
 */
@Controller
public class LoginController {

    @Autowired
    AdminServiceImpl adminService;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/adminLogin")
    public String adminLogin(@RequestParam("account") String account,
                             @RequestParam("password") String password,
                             RedirectAttributes attributes,
                             HttpSession session){

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);

        try {
            subject.login(token);
            Admin admin = adminService.getAdminByAccount(account);
            System.out.println(admin);
            if(!redisUtil.hasKey("headSculpture:admin"+admin.getAdminId().toString())){
                session.setAttribute("img","http://dd.ddandang.top/headportrait/test.jpeg");
            }else{
                session.setAttribute("img",(String) redisUtil.get("headSculpture:admin"+admin.getAdminId().toString()));
            }
            session.setAttribute("admin",admin);
            return "redirect:/backStage.html";
        }catch (UnknownAccountException e){
            attributes.addFlashAttribute("msg","用户名错误!");
            return "redirect:adminLogin.html";
        }catch (IncorrectCredentialsException e){
            attributes.addFlashAttribute("msg","密码错误!");
            return "redirect:adminLogin.html";
        }
    }

    @RequestMapping("backStage.html")
    public String backStage(){
        return "admin/index";
    }

    @RequestMapping("/toAdminLogin")
    public String toAdminLogin(){
        return "redirect:adminLogin.html";
    }
    @RequestMapping("/adminLogin.html")
    public String toAdmin(){
        return "adminLogin";
    }



    @GetMapping("/logout")
    public String logout(Map<String,Object> map,
                         RedirectAttributes attributes){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        attributes.addFlashAttribute("msg","安全退出!");
        return "redirect:adminLogin.html";
    }

    @ResponseBody
    @GetMapping("/admin/adminInfo/changeAdminPassWord")
    public int changeAdminPassword(String account,String oldPassword,String newPassword) {
        Admin admin = adminService.getAdminByAccount(account);
        System.out.println(admin);
        if(!oldPassword.equals(admin.getPassword())){
            return 0;
        }
        else {
            admin.setPassword(newPassword);
            adminService.updateAdmin(admin);
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return 1;
        }
    }

    @PostMapping("/userLogin")
    public String userLogin(@RequestParam("phone") String phone,
                            @RequestParam("password") String password,
                            Map<String,Object> map,
                            HttpSession session){

        User user = userService.getUser(phone);
        if(user==null){
            map.put("message","账号不存在");
            return "login";
        }else {
            if(!password.equals(user.getPassword())){
                map.put("message","密码错误");
                return "login";
            }else {
                String userId = String.valueOf(user.getUserId());

                //如果不存在token则加入
                if(!redisUtil.hasKey(userId)){
                    Map<String, Object> tokenMap = tokenUtil.getMapByUser(user);
                    String token = tokenUtil.createToken(userId,phone,tokenMap);
                    redisUtil.set(userId,token);
                    redisUtil.expire(userId,600);
                }
//                System.out.println(user);
//                System.out.println(user.getAvatar());
                session.setAttribute("userImg",user.getAvatar());
                session.setAttribute("user",user);
                redisUtil.set("user:"+user.getUserId().toString(),user);
//                System.out.println("登录成功！");
//                System.out.println(user);
                return "redirect:main/index.html";
            }
        }

    }

    @GetMapping("/userLogin")
    public String toLogin(){
        return "redirect:login.html";
    }
    @RequestMapping("login.html")
    public String login(){
        return "login";
    }
    @GetMapping("/userLogout")
    public String userLogout(Map<String,Object> map){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        map.put("msg","安全退出！");
        return "redirect:main/index.html";
    }

}
